// 全局常量：全部大写，多个单词之间使用下划线分割 const GOODS_TYPE =1
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

class Promise{
	static resolve(value){
		// 判断value是否是Promise实例
		if(value instanceof Promise) return value;
		// 如果不是Promise实例，返回一个状态为fulfilled,值为value的Promise实例。
		return new Promise(resolve=>resolve(value));
	};
	static reject(value){
		return new Promise((resolve,reject)=>{
			reject(value);
		})
	};
	static all(promises){
		let count = 0;
		let arr = new Array(promises.length);
		return new Promise((resolve,reject)=>{
			promises.forEach((item,index)=>{
				// p1 p2 p3 p4
				item.then(value=>{
					count++;
					arr[index] = value;
					// 如果成功回调函数调用的次数与接收数组的长度相同，则返回成功的Promise
					if(count === promises.length){
						resolve(arr);
					}
				},reason=>{
					reject(reason);
				})
			})
		})
	}
	static race(promises){
		return new Promise((resolve,reject)=>{
			promises.forEach(item=>{
				item.then(resolve,reject);
			})
		})
	}
	constructor(executor) {
		// 设置初始状态
		this.state = PENDING;
		// 设置初始状态值
		this.result = undefined;
		// 用于调用成功与失败回调的属性
		this.callback = [];
		function _resolve(v){
			// 判断状态是否已经被更改
			if(this.state !== PENDING) return;
			this.state = FULFILLED;
			this.result = v;
			this.callback.forEach(item=>item.onResolved());
		}
		function _reject(v){
			if(this.state !== PENDING) return;
			this.state = REJECTED;
			this.result = v;
			this.callback.forEach(item=>item.onRejected());
		}
		try{
			// 调用执行器函数，并传递两个参数（类型为函数）
			executor(_resolve.bind(this),_reject.bind(this));
		}catch (err){
			_reject.call(this,err);
		}
	}
	then(onResolved,onRejected){
		// 判断onResolved是否为函数,如果不是函数设置默认值
		if(!(onResolved instanceof Function)){
			onResolved = value=>value;
		}
		if(!(onRejected instanceof Function)){
			onRejected = reason=>{
				throw reason;
			}
		}
		
		// 返回了一个新的Promise实例
		return new Promise((resolve,reject)=>{
			// 封装
			const _common = function(callback){
				setTimeout(()=>{
					try{
						const value = callback(this.result);
						if(value instanceof Promise) value.then(resolve,reject)
						else resolve(value);
					}catch (e){
						reject(e);
					}
				})
			}
			// 状态为fulfilled调用onResolved
			// 状态为rejected调用onRejected
			if(this.state === FULFILLED){
				_common.call(this,onResolved);
			}else if(this.state === REJECTED){
				_common.call(this,onRejected)
			}else if(this.state === PENDING){// 1
				// 记录如果状态更改为成功需要调用的函数
				// 记录如果状态更改为失败需要调用的函数
				this.callback.push({
					onResolved:_common.bind(this,onResolved),
					onRejected:_common.bind(this,onRejected)
				})
			}
		})
		
	}
	catch(onRejected){
		return this.then(undefined,onRejected);
	}
}



